package cn.edu.zsc.study.framework.security;

import cn.edu.zsc.study.entity.Authority;
import cn.edu.zsc.study.entity.Role;
import cn.edu.zsc.study.entity.User;
import cn.edu.zsc.study.repository.RoleAuthoritiesReposity;
import cn.edu.zsc.study.repository.UserRepository;
import cn.edu.zsc.study.repository.UserRolesReposity;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author harry yao
 */
@AllArgsConstructor
@Service
public class JpaUserDetailsServiceImpl implements UserDetailsService {

    private final UserRepository userRepo;
    private final UserRolesReposity urRepo;
    private final RoleAuthoritiesReposity raRepo;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepo.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        Set<Role> roles = urRepo.getRolesByUserId(user.getId());
        user.setRoles(roles);
        user.authorities = raRepo.selectByUserId(user.id).stream().map(roleAuthority -> Authority.valueOf(roleAuthority.getAuthority())).collect(Collectors.toSet());
        if (user == null) {
           throw new UsernameNotFoundException("用户 '" + username + "' 不存在!");
        }
        return UserDetailsImpl.from(user);
    }
}
